import {Cascader, Dropdown} from "antd";
import React, {useEffect, useState} from "react";
import districtData from '@/assets/data/china_districts.json'

const transformData = (data: any[]) => {
    return data.map((province) => ({
        label: province.name,
        value: province.pid,
        children: province.children?.map((city: { name: string; cid: string; children: { name: string; aid: string; }[]; }) => ({
            label: city.name,
            value: city.cid,
            children: city.children?.map((district: { name: string; aid: string; }) => ({
                label: district.name,
                value: district.aid,
                isLeaf: true, // 设置为 true，表示这是最末级，不再有子项
            })),
        })),
    }));
};

export default function DropDownDistrictSelector({onSelected}: {
    onSelected?: (adcode: string) => void;
}) {
    const [options, setOptions] = useState<any[]>([]);
    const [dropdownOpen, setDropdownOpen] = useState(false);

    useEffect(() => {
        setOptions(transformData(districtData)); // 将原始数据转换成 Cascader 格式
    }, []);

    const handleChange = (_value: string[], selectedOptions: any[]) => {
        const lastOption = selectedOptions[selectedOptions.length - 1];

        // 🚫 不允许选择有 children 的项（即 pid 为 null）
        if (!lastOption.isLeaf) {
            return;
        }

        if (onSelected) {
            onSelected(lastOption.value); // 调用回调函数，传入选中的 aid
        }
        setDropdownOpen(false); // 关闭下拉框
    };

    const dropdownContent = (
        <div style={dropdownContentStyle} >
            <Cascader
                options={options}
                onChange={handleChange}
                placeholder="请选择省/市/区"
                changeOnSelect={false}
                style={{width: 200}}
            />
        </div>
    );

    return (
        <Dropdown
            open={dropdownOpen}
            onOpenChange={setDropdownOpen}
            dropdownRender={() => (
                dropdownContent
            )}
            trigger={["click"]}
            placement="bottom"
        >
            <button className="switch-city-btn">
                切换
            </button>
        </Dropdown>
    )
}

const dropdownContentStyle: React.CSSProperties = {
    padding: 8, background: "transparent", borderRadius: 4
}